import { defineStore } from "pinia"
import { ref } from "vue"
import { pinia } from "@/pinia"
import { 
  getMatchPredictEurope18wanApi, 
  deleteMatchesEurope18wMinMaxApi,
  getFootballEuropeOddsApi,
  getHistoricalEurope29318wanApi,
  updateMatchesEurope18wMinMaxApi,
  getSameEurope293AnalysisApi,
  getMatchesEurope18wMinMaxApi
} from "@/pages/europe18w/apis"
import type { 
  MatchPredictEurope18wanApiCondition, 
  MatchPredictEurope18wanResponseData,
  FootballEuropeOdds
} from "@/pages/europe18w/apis/type"
import type { MatchPredictEurope18wan } from "@/models/matchPredictEurope18wan"

export const useEurope18wStore = defineStore("europe18w", () => {
  // 响应式数据
  const isSearchCollapsed = ref(false)
  const dateRange = ref<[string, string] | null>(null)
  const loading = ref(false)
  const tableData = ref<(MatchPredictEurope18wan & { showAnalysis?: boolean })[]>([])
  const total = ref(0)
  const currentPage = ref(1)
  const expandedRowKeys = ref<number[]>([])

  // 搜索表单
  const searchForm = ref<MatchPredictEurope18wanApiCondition>({
    current_page: 1,
    page_size: 20,
    event_name: null,
    matchtime_s: null,
    matchtime_e: null,
    home_initial_min: null,
    home_initial_max: null,
    draw_initial_min: null,
    draw_initial_max: null,
    away_initial_min: null,
    away_initial_max: null
  })

  // #region Actions

  function toggleSearch() {
    isSearchCollapsed.value = !isSearchCollapsed.value
  }

  async function handleSearch() {
    // 处理时间范围
    if (dateRange.value) {
      searchForm.value.matchtime_s = dateRange.value[0]
      searchForm.value.matchtime_e = dateRange.value[1]
    } else {
      searchForm.value.matchtime_s = null
      searchForm.value.matchtime_e = null
    }

    // 设置当前页为第一页
    searchForm.value.current_page = 1
    currentPage.value = 1

    // 查询数据
    await fetchData()
  }

  function handleReset() {
    // 重置表单
    searchForm.value.event_name = null
    searchForm.value.home_initial_min = null
    searchForm.value.home_initial_max = null
    searchForm.value.draw_initial_min = null
    searchForm.value.draw_initial_max = null
    searchForm.value.away_initial_min = null
    searchForm.value.away_initial_max = null
    dateRange.value = null
    searchForm.value.matchtime_s = null
    searchForm.value.matchtime_e = null

    // 重置分页
    searchForm.value.current_page = 1
    searchForm.value.page_size = 20
    currentPage.value = 1
    total.value = 0
    tableData.value = []
    // Also reset expanded rows
    expandedRowKeys.value = []
  }

  async function handleSizeChange(size: number) {
    searchForm.value.page_size = size
    searchForm.value.current_page = 1
    currentPage.value = 1
    await fetchData()
  }

  async function handleCurrentChange(page: number) {
    searchForm.value.current_page = page
    currentPage.value = page
    await fetchData()
  }

  // 表格行类名，根据 is_setting_range 字段设置不同背景色
  function tableRowClassName({ row }: { row: MatchPredictEurope18wan & { showAnalysis?: boolean } }) {
    if (row.is_setting_range === 1) {
      return 'row-effective' // 最值有效：绿色背景
    }
    return '' // 其他情况无特殊样式（默认背景）
  }

  async function handleDeleteMinMax(fid: number) {
    try {
      const response = await deleteMatchesEurope18wMinMaxApi(fid)
      if (response.code === 0) {
        // 成功后刷新数据
        await fetchData()
        return { success: true, message: '最值无效设置成功' }
      } else {
        return { success: false, message: response.message || '删除失败' }
      }
    } catch (error) {
      console.error('删除失败:', error)
      return { success: false, message: '删除失败，请稍后重试' }
    }
  }

  // 更新指定行的最值状态（在删除后不需要重新获取全部数据）
  function updateRowSettingRange(fid: number, newValue: number) {
    const rowIndex = tableData.value.findIndex(item => item.fid === fid);
    if (rowIndex !== -1) {
      const newData = [...tableData.value];
      newData[rowIndex] = { ...newData[rowIndex], is_setting_range: newValue };
      tableData.value = newData;
    }
  }

  // 切换最值状态（设置/取消设置最值）
  async function toggleSettingRange(fid: number) {
    try {
      const response = await deleteMatchesEurope18wMinMaxApi(fid)
      if (response.code === 0) {
        // 更新本地状态而不重新获取所有数据
        const rowIndex = tableData.value.findIndex(item => item.fid === fid);
        if (rowIndex !== -1) {
          const newData = [...tableData.value];
          // 翻转状态：1变0，0变1（根据业务逻辑判断，API调用后状态应该是相反的）
          const currentStatus = newData[rowIndex].is_setting_range;
          newData[rowIndex] = { 
            ...newData[rowIndex], 
            is_setting_range: currentStatus === 1 ? 0 : 1 
          };
          tableData.value = newData;
        }
        return { success: true, message: response.message || '状态更新成功' };
      } else {
        return { success: false, message: response.message || '操作失败' };
      }
    } catch (error) {
      console.error('切换状态失败:', error);
      return { success: false, message: '操作失败，请稍后重试' };
    }
  }

  // 以下为分析详情相关状态和方法
  const analysisDetailState = ref({
    oddsData: [] as FootballEuropeOdds[], // FootballEuropeOdds[]
    analysisResult: null as any, // AnalysisResult | null
    minMaxSettings: {
      fid: 0,
      home_odds_min: null,
      home_odds_max: null,
      draw_odds_min: null,
      draw_odds_max: null,
      away_odds_min: null,
      away_odds_max: null
    },
    loading: false,
    analysisLoading: false,
    saveLoading: false,
    hasMinMaxData: false
  })

  // 加载赔率数据
  async function loadOddsDataForAnalysis(fid: number) {
    if (!fid) {
      console.error('缺少比赛ID')
      return { success: false, message: '缺少比赛ID' }
    }

    analysisDetailState.value.loading = true
    try {
      const response = await getFootballEuropeOddsApi({ fid })
      if (response.code === 0) {
        analysisDetailState.value.oddsData = response.data || []
        return { success: true, data: response.data }
      } else {
        return { success: false, message: response.message || '获取赔率数据失败' }
      }
    } catch (error) {
      console.error('获取赔率数据失败:', error)
      return { success: false, message: '获取赔率数据失败' }
    } finally {
      analysisDetailState.value.loading = false
    }
  }

  // 计算返还率
  function calculateReturnRate(row: any) { // FootballEuropeOdds
    if (row.home_odds && row.draw_odds && row.away_odds) {
      const total = 1 / row.home_odds + 1 / row.draw_odds + 1 / row.away_odds
      return (1 / total * 100).toFixed(2)
    }
    return '0.00'
  }

  // 执行分析
  async function handleAnalysisForDetail(fid: number) {
    analysisDetailState.value.analysisLoading = true
    try {
      // 构建查询条件，使用最值设置
      const condition: any = { // SameEurope293AnalysisCondition
        fid: fid
      }

      const response = await getSameEurope293AnalysisApi(condition)
      if (response.code === 0 && response.data && response.data.length > 0) {
        const data = response.data[0]

        // 更新统计区域显示字段
        analysisDetailState.value.analysisResult = {
          stats: {
            total_matches: data.total_matches || 0,
            home_wins: data.home_win_count || 0,
            draws: data.draw_count || 0,
            away_wins: data.away_win_count || 0,
            home_win_rate: data.home_win_rate || 0,
            draw_rate: data.draw_rate || 0,
            away_win_rate: data.away_win_rate || 0,
            home_initial: data.home_initial,
            theory_home_initial: data.theory_home_initial,
            home_diff: data.home_diff,
            draw_initial: data.draw_initial,
            theory_draw_initial: data.theory_draw_initial,
            draw_diff: data.draw_diff,
            away_initial: data.away_initial,
            theory_away_initial: data.theory_away_initial,
            away_diff: data.away_diff
          },
          matches: [] // 接口不返回matches数据，所以为空
        }

        return { success: true, message: '分析完成' }
      } else if (response.code === 0 && response.data && response.data.length === 0) {
        // 当接口返回成功但数据为空时，也设置 analysisResult 为 null
        analysisDetailState.value.analysisResult = null
        return { success: false, message: '暂无分析数据' }
      } else {
        return { success: false, message: response.message || '分析失败或无数据' }
      }
    } catch (error) {
      console.error('分析失败:', error)
      return { success: false, message: '分析失败' }
    } finally {
      analysisDetailState.value.analysisLoading = false
    }
  }

  // 计算统计数据
  function calculateStats(matches: any[]) { // MatchPredictEurope29318wan[]
    const total = matches.length
    const homeWins = matches.filter(match =>
      match.homescore !== null && match.awayscore !== null && match.homescore > match.awayscore
    ).length
    const draws = matches.filter(match =>
      match.homescore !== null && match.awayscore !== null && match.homescore === match.awayscore
    ).length
    const awayWins = total - homeWins - draws

    return {
      total_matches: total,
      home_wins: homeWins,
      draws: draws,
      away_wins: awayWins,
      home_win_rate: total > 0 ? (homeWins / total * 100) : 0,
      draw_rate: total > 0 ? (draws / total * 100) : 0,
      away_win_rate: total > 0 ? (awayWins / total * 100) : 0
    }
  }

  // 保存设置
  async function handleSaveMinMax(fid: number) {
    if (!fid) {
      return { success: false, message: '缺少比赛ID' }
    }

    analysisDetailState.value.saveLoading = true
    try {
      const requestData = {
        ...analysisDetailState.value.minMaxSettings,
        fid: fid
      }

      const response = await updateMatchesEurope18wMinMaxApi(requestData)
      if (response.code === 0) {
        // 更新主表格数据中的is_setting_range字段
        const tableIndex = tableData.value.findIndex(item => item.fid === fid);
        if (tableIndex !== -1) {
          const newTableData = [...tableData.value];
          newTableData[tableIndex] = { ...newTableData[tableIndex], is_setting_range: 1 };
          tableData.value = newTableData;
        }
        
        // 重新加载最值数据 to ensure consistency with backend
        await loadMinMaxDataForAnalysis(fid)
        return { success: true, message: '保存成功' }
      } else {
        return { success: false, message: response.message || '保存失败' }
      }
    } catch (error) {
      console.error('保存失败:', error)
      return { success: false, message: '保存失败' }
    } finally {
      analysisDetailState.value.saveLoading = false
    }
  }

  // 最值无效
  async function handleDeleteMinMaxFromAnalysis(fid: number) {
    if (!fid) {
      return { success: false, message: '缺少比赛ID' }
    }

    try {
      const response = await deleteMatchesEurope18wMinMaxApi(fid)
      if (response.code === 0) {
        // 先清空本地最值设置，再重新加载数据
        analysisDetailState.value.minMaxSettings.home_odds_min = null
        analysisDetailState.value.minMaxSettings.home_odds_max = null
        analysisDetailState.value.minMaxSettings.draw_odds_min = null
        analysisDetailState.value.minMaxSettings.draw_odds_max = null
        analysisDetailState.value.minMaxSettings.away_odds_min = null
        analysisDetailState.value.minMaxSettings.away_odds_max = null
        analysisDetailState.value.hasMinMaxData = false
        
        // 更新主表格数据中的is_setting_range字段
        const tableIndex = tableData.value.findIndex(item => item.fid === fid);
        if (tableIndex !== -1) {
          const newTableData = [...tableData.value];
          newTableData[tableIndex] = { ...newTableData[tableIndex], is_setting_range: 0 };
          tableData.value = newTableData;
        }
        
        // 重新加载最值数据 to ensure consistency with backend
        await loadMinMaxDataForAnalysis(fid)
        return { success: true, message: '最值无效设置成功' }
      } else {
        return { success: false, message: response.message || '删除失败' }
      }
    } catch (error) {
      console.error('删除失败:', error)
      return { success: false, message: '删除失败' }
    }
  }

  // 格式化日期时间
  function formatDateTime(dateTime: string | null) {
    if (!dateTime) return '-'
    try {
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    } catch {
      return dateTime
    }
  }

  // 加载最值数据
  async function loadMinMaxDataForAnalysis(fid: number) {
    if (!fid) {
      console.warn('缺少比赛ID，无法加载最值数据')
      return
    }

    try {
      const response = await getMatchesEurope18wMinMaxApi({ fid })
      if (response.code === 0 && response.data) {
        // 将接口返回的数据填充到 minMaxSettings
        analysisDetailState.value.minMaxSettings.home_odds_min = response.data.home_odds_min
        analysisDetailState.value.minMaxSettings.home_odds_max = response.data.home_odds_max
        analysisDetailState.value.minMaxSettings.draw_odds_min = response.data.draw_odds_min
        analysisDetailState.value.minMaxSettings.draw_odds_max = response.data.draw_odds_max
        analysisDetailState.value.minMaxSettings.away_odds_min = response.data.away_odds_min
        analysisDetailState.value.minMaxSettings.away_odds_max = response.data.away_odds_max

        // 检查是否存在最值数据，只要有任意一个最值存在，就认为有最值数据
        analysisDetailState.value.hasMinMaxData = (
          response.data.home_odds_min !== null ||
          response.data.home_odds_max !== null ||
          response.data.draw_odds_min !== null ||
          response.data.draw_odds_max !== null ||
          response.data.away_odds_min !== null ||
          response.data.away_odds_max !== null
        )
      } else {
        // 如果接口返回失败或数据为空，清空本地最值设置
        analysisDetailState.value.minMaxSettings.home_odds_min = null
        analysisDetailState.value.minMaxSettings.home_odds_max = null
        analysisDetailState.value.minMaxSettings.draw_odds_min = null
        analysisDetailState.value.minMaxSettings.draw_odds_max = null
        analysisDetailState.value.minMaxSettings.away_odds_min = null
        analysisDetailState.value.minMaxSettings.away_odds_max = null
        analysisDetailState.value.hasMinMaxData = false
      }
    } catch (error) {
      console.error('获取最值数据异常:', error)
      analysisDetailState.value.hasMinMaxData = false
    }
  }

  // 初始化分析详情数据
  async function initializeAnalysisDetailData(fid: number) {
    // 重置 minMaxSettings 以确保不保留之前的数据
    analysisDetailState.value.minMaxSettings = {
      home_odds_min: null,
      home_odds_max: null,
      draw_odds_min: null,
      draw_odds_max: null,
      away_odds_min: null,
      away_odds_max: null
    }
    
    await Promise.all([
      loadOddsDataForAnalysis(fid),
      loadMinMaxDataForAnalysis(fid)
    ])
  }



  async function fetchData() {
    try {
      loading.value = true
      const response: MatchPredictEurope18wanResponseData = await getMatchPredictEurope18wanApi(searchForm.value)

      if (response.code === 0) {
        // Preserve the expansion state when updating table data
        const expandedFids = new Set(expandedRowKeys.value);
        tableData.value = (response.data || []).map(item => ({
          ...item,
          showAnalysis: expandedFids.has(item.fid) || false
        }))
        total.value = response.pagination?.total || 0
        currentPage.value = response.pagination?.current_page || 1
      } else {
        console.error(response.message || '查询失败')
        return { success: false, message: response.message || '查询失败' }
      }
    } catch (error) {
      console.error('查询数据失败:', error)
      return { success: false, message: '查询失败，请稍后重试' }
    } finally {
      loading.value = false
    }
  }

  function toggleAnalysis(row: MatchPredictEurope18wan & { showAnalysis?: boolean }) {
    // Update the showAnalysis state for the button text
    const index = tableData.value.findIndex(item => item.fid === row.fid);
    if (index !== -1) {
      const newRow = { ...tableData.value[index] };
      newRow.showAnalysis = !newRow.showAnalysis;
      const newTableData = [...tableData.value];
      newTableData[index] = newRow;
      tableData.value = newTableData;
    }

    // Toggle the expanded row keys
    const fid = row.fid;
    const isCurrentlyExpanded = expandedRowKeys.value.includes(fid);

    if (isCurrentlyExpanded) {
      // Remove from expanded keys to collapse
      expandedRowKeys.value = expandedRowKeys.value.filter(key => key !== fid);
    } else {
      // Add to expanded keys to expand
      expandedRowKeys.value = [...expandedRowKeys.value, fid];
    }
  }

  // 设置默认时间范围为最近90天 (不再限制为一个月), 用户可以选择任意范围包括清空日期进行全量搜索
  function setDefaultDateRange() {
    const endDate = new Date()
    const startDate = new Date()
    startDate.setDate(startDate.getDate() - 90)

    dateRange.value = [
      startDate.toISOString().split('T')[0],
      endDate.toISOString().split('T')[0]
    ]

    searchForm.value.matchtime_s = dateRange.value[0]
    searchForm.value.matchtime_e = dateRange.value[1]
  }

  // 初始化数据 - 这个方法应该在组件挂载时调用
  async function initializeData() {
    // Set default date range on initialization but users can clear it to search all dates
    setDefaultDateRange()
    await fetchData()
  }

  // #endregion

  return {
    // State
    isSearchCollapsed,
    dateRange,
    loading,
    tableData,
    total,
    currentPage,
    expandedRowKeys,
    searchForm,

    // Analysis Detail State
    analysisDetailState,

    // Actions
    toggleSearch,
    handleSearch,
    handleReset,
    handleSizeChange,
    handleCurrentChange,
    tableRowClassName,
    handleDeleteMinMax,
    toggleSettingRange,
    fetchData,
    toggleAnalysis,
    setDefaultDateRange,
    initializeData,

    // Analysis Detail Actions
    loadOddsDataForAnalysis,
    calculateReturnRate,
    handleAnalysisForDetail,
    calculateStats,
    handleSaveMinMax,
    handleDeleteMinMaxFromAnalysis,
    formatDateTime,
    loadMinMaxDataForAnalysis,
    initializeAnalysisDetailData
  }
})

export function useEurope18wStoreOutside() {
  return useEurope18wStore(pinia)
}